﻿namespace 可为空的引用类型
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student();
            Console.WriteLine(s.Name);  //不会报错
            //Console.WriteLine(s.Name.ToLower());    //会报错，提示可能为空引用异常
            Console.WriteLine(s.Name?.ToLower());    //不会报错。使用?.操作符可以避免空引用异常

            Console.WriteLine(s.Name!.ToString());  //不会报错。使用!操作符告诉编译器该引用类型不为空.但是在运行时如果为空则会抛出异常
            Console.WriteLine("Hello, World");


            //下面的三行代码不会报错
            Teacher t = new Teacher(null, null);
            Console.WriteLine(t.Name);
            Console.WriteLine(t.Address);
        }
    }

    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

    class Teacher
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string? Address { get; set; }
        public Teacher(string name, string address)
        {
            Name = name;
            Address = address;
        }
    }

    class Person
    {
        public int Id { get; set; }
        public string Name { get; init; }
        public Person(int id, string name)
        {
            Id = id;
            Name = name;
        }

        public void F()
        {
            //Name = "New Name"; //会报错，init属性只能在对象初始化时赋值
        }
    }
}
